// 将文件转换成不带MIME的base64
export function convertFileToBase64WithoutMIME(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(String(reader.result).split(",")[1])
        reader.onerror = (error) => reject(error)
    })
}


// 将文件转换成不带MIME的base64并压缩
export function compressImageToBase64(
    file: File,
    maxWidth = 800,
    maxHeight = 800,
    quality = 0.9
  ): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (event) {
        if (!event.target) return;
        const img = new Image();
        img.src = event.target.result as string;
        img.onload = () => {
          // Calculate the new size with max dimensions
          let width = img.width;
          let height = img.height;
  
          if (width > height) {
            if (width > maxWidth) {
              height = Math.round((height *= maxWidth / width));
              width = maxWidth;
            }
          } else {
            if (height > maxHeight) {
              width = Math.round((width *= maxHeight / height));
              height = maxHeight;
            }
          }
  
          const canvas = document.createElement("canvas");
          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext("2d");
          if (!ctx) return;
          ctx.drawImage(img, 0, 0, width, height);
  
          // Get the base64 URL of the compressed image
          resolve(canvas.toDataURL("image/jpeg", quality));
        };
      };
      reader.onerror = (error) => reject(error);
    });
  }